﻿using NB.MGJ.Common.Helper;
using NB.MGJ.Common.Utility;
using NB.MGJ.Model;
using NB.MGJ.Model.AntiFleeingEntity;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace NB.MGJ.Web.Controllers
{
    /// <summary>
    /// 窜货
    /// </summary>
    /// =======================================================================
    /// 类名：DemoService DemoController的备注：DemoService~1<br/>
    /// =======================================================================<br/>
    /// 更新履历<br/>
    /// 序号          更新日期          责任人           更新内容<br/>
    /// 001           2017/08/30        华君             装箱<br/>
    /// 002           2017/08/31        华君             调拨<br/>
    /// 003           2017/08/31        华君             退货<br/>
    /// 004           2017/09/05        华君             出库<br/>
    /// 005           2017/09/06        华君             处理状态<br/>
    /// 006           2017/09/07        华君             窜货验证<br/>
    /// 007           2017/10/09        华君             操作记录<br/>
    /// 008           2017/12/20        华君             修改获取最小标的方法<br/>
    /// 009           2017/12/20        华君             拆箱<br/>
    /// =======================================================================<br/>
    /// 

    ///冻结说明 当用户申请调货和退货时，会将该产品所对应的码进行冻结 且冻结后不可做任何仓库操作
    ///解冻说明 用户撤销申请或申请单被处理（处理状态无论成败）或申请过期 则码会被解除冻结状态
    public partial class FleeGoodsController
    {
        #region 下拉框绑定方法
        //绑定产品下拉框
        public List<SelectListItem> SelProductList(string proId)
        {
            if (string.IsNullOrEmpty(proId))
            {
                proId = "0";
            }
            List<Product_Product> result = new List<Product_Product>();
            if (LogOnUser.Distributor != 0)//经销商
            {
                result = _mservice.GetProcductService(LogOnUser.UserID);
            }
            else
            {
                //查询某机构下的所有仓库 包括其下级机构的仓库
                result = _mservice.GetProcductService(LogOnUser.JuniorEnterprise);
            }
            List<SelectListItem> items = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem() { Text = result[i].ProductName, Value = result[i].Id.ToString(), Selected = (proId.Contains(result[i].Id.ToString())) };
                items.Add(item);
            }
            return items;
        }
        //绑定仓库下拉框 
        public List<SelectListItem> SelWarehouseList(int WarehouseId, int GoWarehouseId = 0)
        {
            List<AntiFleeing_Warehouse> result = new List<AntiFleeing_Warehouse>();
            if (LogOnUser.Distributor != 0)//经销商
            {
                result = _mservice.GetWarehouseService(LogOnUser.UserID, GoWarehouseId, WarehouseId);
            }
            else
            {
                //查询某机构下的所有仓库 包括其下级机构的仓库
                result = _mservice.GetWarehouseService(LogOnUser.JuniorEnterprise, GoWarehouseId, WarehouseId);

            }

            List<SelectListItem> items = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem() { Text = result[i].WarehouseName, Value = result[i].ID.ToString() };
                if (WarehouseId == result[i].ID)
                {
                    item.Selected = true;
                }
                items.Add(item);
            }
            return items;
        }
        //绑定片区
        public List<SelectListItem> SelSaleAreaList(int SaleAreaId)
        {
            List<AntiFleeing_SalesArea> result = new List<AntiFleeing_SalesArea>();
            if (LogOnUser.Distributor != 0)//经销商
            {
                result = _mservice.GetSaleAreaService(LogOnUser.Distributor);
            }
            else
            {
                if (LogOnUser.EnterpriseId == 1)//管理员
                {
                    result = _mservice.GetSaleAreaService();
                }
                //查询某机构下的所有片区 包括其下级机构的片区
                else
                    result = _mservice.GetSaleAreaService(LogOnUser.JuniorEnterprise);
            }

            List<SelectListItem> items = new List<SelectListItem>();
            //  items.Add(new SelectListItem() { Text = "请选择", Value ="0" });
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem() { Text = result[i].Name, Value = result[i].ID.ToString() };
                if (SaleAreaId == result[i].ID)
                {
                    item.Selected = true;
                }
                items.Add(item);
            }
            return items;
        }
        //经销商
        public JsonResult SelDistributorList(int SaleAreaId, int disId)
        {
            List<AntiFleeing_Distributor> result = new List<AntiFleeing_Distributor>();
            if (LogOnUser.Distributor != 0)//经销商
            {
                result = _mservice.GetDistributorService_Disc(SaleAreaId, LogOnUser.Distributor);
            }
            else
            {
                result = _mservice.GetDistributorService(SaleAreaId);
            }
            List<SelectListItem> items = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem() { Text = result[i].Name, Value = result[i].Id.ToString() };
                if (disId == result[i].Id)
                {
                    item.Selected = true;
                }
                items.Add(item);
            }
            if (result.Count == 0) items.Add(new SelectListItem() { Text = "无", Value = "" });//此处value值千万千万别加空格了
            return Json(items);
        }
        #endregion

        #region 装箱
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public ActionResult PackBoxUploadTxt(string filePath, int isGo = 0)
        {
            if (LogOnUser.EnterpriseId != 1)
            {
                return Json(-1);
            }
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_PackBox model = new AntiFleeing_PackBox();
            int id = 0;
            if (filePath != "")
            {
                //保存数据
                model.CreateLoginID = userModel.UserID;
                model.CreateLoginName = userModel.LoginName;
                model.CreateDate = DateTime.Now;
                model.FilePath = filePath;
                model.ViewDel = 0;
                model.ChangeDate = DateTime.Now;
                model.Status = 1;
                model.Type = 1;
                StreamReader fsRead = new StreamReader(filePath, System.Text.Encoding.Default);
                Dictionary<string, int> dic = new Dictionary<string, int>();
                string strTxt = string.Empty;
                string code = string.Empty;
                string codeType = string.Empty;
                int len = 0;
                int n = 0;
                while (!fsRead.EndOfStream)
                {
                    strTxt = fsRead.ReadLine().Trim();//读取一行数据
                    string[] strTxts = strTxt.Split(',');
                    code = strTxts[0];
                    if (n == 0)
                    {
                        AntiFleeing_PackBox packbox = _mservice.GetGenCodeInfo(code);
                        if (packbox == null)
                        {
                            fsRead.Close();
                            return Json(-2);
                        }
                        model.CodeType = packbox.CodeType;
                        model.GenCodeNum = packbox.GenCodeNum;
                        model.Bacth = code.Substring(4, AppConst.SubBatchLen);
                        model.EnterpriseID = packbox.EnterpriseID;
                        if (LogOnUser.EnterpriseId != model.EnterpriseID && LogOnUser.EnterpriseId != 1)
                        {
                            fsRead.Close();
                            return Json(-2);
                        }
                        if (isGo == 0)
                        {
                            var packBoxInfo = _mservice.PackBoxInfo(packbox.EnterpriseID.Value, model.Bacth);
                            if (packBoxInfo != null)
                            {
                                fsRead.Close();
                                return Json(-4);//当前批次已装箱
                            }
                        }

                        model.FormCode = "ZX" + GetTimestamp(DateTime.Now);
                    }
                    for (int i = 0; i < strTxts.Length; i++) //除以二可以得到拖带级数
                    {
                        len = strTxts.Length / 2;

                        if (i % 2 == 0) //奇数 为物流码 从零开始
                        {
                            if (dic.ContainsKey(strTxts[i])) dic[strTxts[i]] = (dic[strTxts[i]] + 1);
                            else dic.Add(strTxts[i], 1);
                        }
                    }
                    n++;
                }
                fsRead.Close();
                //根据物流码得到生码信息
                string str = "";
                //统计
                var list = dic.GroupBy(kvp => kvp.Value).ToList();
                Dictionary<int, int> dict = new Dictionary<int, int>();
                foreach (var item in list)
                {
                    dict.Add(item.Key, 1);
                    str += item.Key + ",";
                    foreach (var subitem in item)
                    {
                        dict[item.Key]++;
                    }
                }
                string[] arr = str.TrimEnd(',').Split(',');
                string strr = "1-";
                for (int i = 0; i < arr.Length - 1; i++)
                {
                    int a = int.Parse(arr[i]);
                    int b = int.Parse(arr[i + 1]);
                    strr += a / b + "-";
                }
                model.ScalingRelation = strr.TrimEnd('-');
                model.Type = 1;//批量
                foreach (KeyValuePair<int, int> a in dict)
                {
                    model.Explain += a.Value + "-";
                }
                model.Explain = model.Explain.TrimEnd('-');
                model.Num = int.Parse(model.Explain.Split('-')[0]);
                model = WipeNullHelper.WipeNull<AntiFleeing_PackBox>(model);//去空
                id = _mservice.PackBoxAdd(model);
            }
            return Json(id);
        }
        // 分页查询
        public ActionResult PackBoxPageList(SearchModel SearchModel, int pageIndex = 1, int pageSize = 15)
        {
            var userid = LogOnUser.UserID;
            var enterpriseId = LogOnUser.EnterpriseId;
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = "   ID" + " " + "DESC";
            if (LogOnUser.Distributor != 0)//经销商
            {
                pm.StrCondition = string.Format(" W.CREATELOGINID in (select ID from sys_user where FIND_IN_SET(distributor,getDiscChild({0})))", LogOnUser.Distributor);

            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise))
                        pm.StrCondition = "  (W.ENTERPRISEID  IN (0))";
                    else
                        pm.StrCondition = "  (W.ENTERPRISEID IN (" + LogOnUser.JuniorEnterprise + "))";
                }
                else pm.StrCondition = "  1=1";
            }
            var result = _mservice.PackBoxGetPageList(ref pm, SearchModel);
            return Json(result);
        }
        //编辑
        public ActionResult EditPacking(int? id)
        {
            var model = _mservice.PackBoxGetModel(id.ToString());
            return View(model);
        }
        public ActionResult BoxShowData(int? id = 0)
        {
            var model = _mservice.GetShowData<V_PackBox>((int)id, "V_PackBox");
            ViewBag.model = model;
            return View(model);
        }
        //少量装箱
        public ActionResult LittlePackingAdd(int? ID, string BoxCode, string SingleCodes)
        {
            SingleCodes = SingleCodes.Replace("\n", "");
            SingleCodes = SingleCodes.Replace("\r", "");
            SingleCodes = SingleCodes.Replace("\t", "");
            SingleCodes = SingleCodes.Replace("，", ",");
            if (SingleCodes.IndexOf(BoxCode) != -1) return Json("{'id':-1,'text':'单标与箱标不能重复！'}");
            var list = new List<V_ListBox>();
            string result = Check_Out(BoxCode, out list);
            if (!string.IsNullOrEmpty(result)) return Json("{'id':-1,'text':'" + result + "'}");

            LogOnUserModel userModel = LogOnUser;
            string[] arr = SingleCodes.TrimEnd(',').Split(',');
            Hashtable ht = new Hashtable();
            for (int i = 0; i < arr.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(arr[i].Trim()))
                {
                    return Json("{'id':-1,'text':'第" + i + "个码后面存在多余的字符！'}");
                }
                var _list = new List<V_ListBox>();
                string _result = Check_Out(arr[i], out _list);
                if (!string.IsNullOrEmpty(result)) return Json("{'id':-1,'text':'" + _result + "'}");
                //重复装箱提示 
                if (_list[_list.Count - 1].ParentCode != null)
                {
                    if (_list[_list.Count - 1].ParentCode == "0")
                    {
                        //防止出现死循环
                        int count = list.FindAll(m => m.Wl_Code == arr[i]).Count;
                        if (count > 0)
                        {
                            return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已装箱！'}");
                        }
                    }
                    else
                    {
                        return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已装箱！'}");
                    }

                }

                string tableName = "nbcodemain.AntiFake_Digitcode" + arr[i].Substring(0, AppConst.SubStrLen);
                ht.Add("update " + tableName + " set ParentCode='" + BoxCode + "' where Wl_Code='" + arr[i] + "'", null);
            }
            AntiFleeing_PackBox model = _mservice.GetGenCodeInfo(BoxCode.TrimStart());
            model.FilePath = _mservice.WriteTxt(arr, "ZX" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
            model.Type = 3;//少量
            model.EnterpriseID = LogOnUser.EnterpriseId;
            //model.FormCode = "ZX" + GetTimestamp(DateTime.Now);
            model.FormCode = DateTime.Now.ToString("yyyyMMddHHmmss");
            model.CreateLoginID = userModel.UserID;
            model.CreateLoginName = userModel.LoginName;
            model.CreateDate = DateTime.Now;
            model.ViewDel = 0;
            model.ScalingRelation = "1-" + arr.Length;
            model.Num = 1;
            model.Status = 2;
            model.Explain = BoxCode + "," + SingleCodes;
            model.ChangeLoginID = userModel.UserID;
            model.ChangeLoginName = userModel.LoginName;
            model.ChangeDate = DateTime.Now;
            model.Bacth = BoxCode.TrimStart().Substring(4, AppConst.SubBatchLen);
            int id = 0;
            if (ID == 0)
            {
                model = WipeNullHelper.WipeNull<AntiFleeing_PackBox>(model);//去空
                id = _mservice.PackBoxAdd(model);
                if (id > 0)
                {  //改变生码表信息
                    _mservice.littleUpload(ht);
                    //添加装箱记录
                    AntiFleeing_DevanningRecords record = new AntiFleeing_DevanningRecords();
                    record.CZCode = BoxCode;
                    record.GLCode = arr.ToString();
                    record.Type = 3;//少量装箱
                    record.CreateBy = LogOnUser.UserID;
                    record.CreateByName = LogOnUser.RealName;
                    record.CreateOn = DateTime.Now;
                    _mservice.RecordAdd(record);
                    for (int i = 0; i < arr.Length; i++)
                    {
                        record = new AntiFleeing_DevanningRecords();
                        record.CZCode = arr[i];
                        record.GLCode = BoxCode;
                        record.Type = 3;//少量装箱
                        record.CreateBy = LogOnUser.UserID;
                        record.CreateByName = LogOnUser.RealName;
                        record.CreateOn = DateTime.Now;
                        _mservice.RecordAdd(record);
                    }
                    return Json("{'id':1,'text':'添加成功!'}");
                }
                else
                {
                    return Json("{'id':1,'text':'添加失败!'}");
                }
            }
            else
            {
                model.ID = ID;
                model.ChangeLoginID = userModel.UserID;
                model.ChangeLoginName = userModel.LoginName;
                model.ChangeDate = DateTime.Now;
                id = _mservice.PackBoxUpdate(model);
                if (id > 0)
                {
                    return Json("修改成功!");
                }
                else
                {
                    return Json("修改失败!");
                }
            }
        }
        public ActionResult DelPacking(int? id)
        {
            AntiFleeing_PackBox model = new AntiFleeing_PackBox();
            model.ID = id;
            model.ViewDel = 1;
            int i = _mservice.PackBoxUpdate(model);
            return Json(i);
        }
        #endregion

        #region 产品调拨
        //上传物流码
        public ActionResult AlloInfoUploadTxt(string filePath)
        {
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_Allocation model = new AntiFleeing_Allocation();
            if (filePath != null)
            {
                StreamReader fsRead = new StreamReader(filePath, System.Text.Encoding.Default);
                string code = string.Empty;
                int n = 0;
                while (!fsRead.EndOfStream)
                {
                    code = fsRead.ReadLine().TrimEnd(',');//读取一行数据
                    if (n == 0)
                    {
                        code = code.Replace("\t", "");
                        code = code.Replace("\n", "");
                        code = code.Replace("\r", "");
                        code = code.Replace("，", ",");
                        Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
                        if (code.Trim().Substring(0, 4) != ent.Code)
                        {
                            model.ViewDel = 1;
                            _mservice.AllocationUpdate(model);
                            fsRead.Close();
                            return Json(-2);
                        }
                        var list = _mservice.ListGetTable(code);
                        //判断是否冻结
                        if (list[0].Flag != 0)
                        {
                            fsRead.Close();
                            return Json(-4);
                        }
                        //当前码的最小标数量
                        model.DragNum = list.GroupBy(m => m.levv).Select(m => new
                        {
                            lev = m.Key,
                            count = m.Count(),
                        }).OrderBy(m => m.lev).Last().count;
                        code = list[0].Wl_Code;
                        //如果是经销商 则判断厂家是否给他出过库
                        if (LogOnUser.Distributor != 0)
                        {
                            var outInfo = _mservice.GetOutTable(code);
                            if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                            {
                                fsRead.Close();
                                return Json(-3);//您尚未权限操作该码
                            }
                            //存在出库信息
                            bool isHas = _mservice.GetIntoInfo(code, LogOnUser.UserID.ToString());//查询入库信息
                            if (!isHas)
                            {
                                return Json(-1);//物流码尚未入库
                            }

                        }
                        AntiFleeing_IOWarehouse dig = _mservice.GetIOWarehouseInfo(code, LogOnUser.EnterpriseId);
                        if (dig == null)
                        {
                            fsRead.Close();
                            return Json(-1);//物流码尚未入库
                        }
                        model.ProductID = dig.ProductID.ToString();
                        model.FromWarehouseId = dig.WarehouseId;
                        //count = _mservice.SearchChildrenCount(code);
                    }
                    n++;
                }
                fsRead.Close();
                model.Num = n;
                //估算的最小标数量
                model.DragNum = n * model.DragNum;
                //保存数据
                model.EnterpriseID = userModel.EnterpriseId;
                model.CreateLoginID = userModel.UserID;
                model.CreateLoginName = userModel.RealName ?? userModel.LoginName;
                model.CreateDate = DateTime.Now;
                model.FilePath = filePath;
                model.ViewDel = 0;
                model.ChangeDate = DateTime.Now;
                model.ChangeLoginID = userModel.UserID;
                model.ChangeLoginName = userModel.RealName ?? userModel.LoginName;
                model.Status = 0;//待编辑
                model.Type = 1;
                //model.FormCode = "DB" + GetTimestamp(DateTime.Now);
                model = WipeNullHelper.WipeNull<AntiFleeing_Allocation>(model);//去空
                model.ID = _mservice.AllocationAdd(model);
                return Json(model.ID);
            }
            else
            {
                return Json(-1);
            }
        }
        // 填写物流码
        public ActionResult AlloLittleCode(string BoxCode)
        {
            BoxCode = BoxCode.Replace("\t", "");
            BoxCode = BoxCode.Replace("\n", "");
            BoxCode = BoxCode.Replace("\r", "");
            BoxCode = BoxCode.Replace("，", ",");
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_Allocation model = new AntiFleeing_Allocation();
           // model.FormCode = "DB" + GetTimestamp(DateTime.Now);
            string[] arr = BoxCode.TrimEnd(',').Split(',');
            Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息

            model.DragNum = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(arr[i].Trim()))
                {
                    return Json("{'id':-1,'text':'第" + i + "个码后面存在多余的字符！'}");
                }
                if (arr[i].Trim().Substring(0, 4) != ent.Code)
                {
                    return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码不属于当前企业！'}");
                }
                var list = _mservice.ListGetTable(arr[i]);
                //判断是否冻结
                if (list[0].Flag != 0) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已冻结！'}");
                var parentCode = list[0].Wl_Code;
                if (parentCode != arr[i]) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码请分离后再操作！'}");
                //当前码的最小标数量
                model.DragNum += list.GroupBy(m => m.levv).Select(m => new
                {
                    lev = m.Key,
                    count = m.Count(),
                }).OrderBy(m => m.lev).Last().count;
                //如果是经销商 则判断厂家是否给他出过库
                var outInfo = _mservice.GetOutTable(parentCode);
                if (LogOnUser.Distributor != 0)
                {
                    if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                    {
                        return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码您尚未权限操作！'}");//您尚未权限操作该码
                    }
                    bool isHas = _mservice.GetIntoInfo(parentCode, LogOnUser.UserID.ToString());//查询入库信息
                    if (!isHas)
                    {
                        return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码未入库或不存在！'}");
                    }
                }
                else
                {
                    if (outInfo != null && outInfo.DistributorID != LogOnUser.Distributor)
                    {
                        return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已出库！'}");
                    }
                }
                var dt = _mservice.GetIOWarehouseInfo(parentCode, LogOnUser.EnterpriseId);
                if (dt == null)
                {
                    return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码未入库或不存在！'}");
                }
                string proId = dt.ProductID;
                if (i == 0)
                {
                    model.ProductID = proId;
                    model.FromWarehouseId = dt.WarehouseId;
                }
                if (model.ProductID != proId)
                {
                    return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码与其他码绑定的产品不同！'}");
                }

            }

            model.FilePath = _mservice.WriteTxt(arr, "DB" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
            model.Type = 2;
            model.EnterpriseID = userModel.EnterpriseId;
            model.CreateLoginID = userModel.UserID;
            model.CreateLoginName = userModel.RealName ?? userModel.LoginName;
            model.CreateDate = DateTime.Now;
            model.ViewDel = 0;
            model.Num = arr.Length;
            model.Status = 0;//待编辑
            //model.DragNum = count;
            int id = _mservice.AllocationAdd(model);
            return Json("{'id':" + id + "}");
        }
        //分页查询
        public ActionResult AlloPageList(SearchModel SearchModel, int pageIndex = 1, int pageSize = 15)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = "  ID" + " " + "desc";
            if (LogOnUser.Distributor != 0)//经销商
            {
                // pm.StrCondition = " w.CreateLoginID=" + LogOnUser.UserID + " or  w.CreateLoginID in (select ID from sys_user where  ViewDel=0 and ChangeLoginID=" + LogOnUser.UserID + ")";
                pm.StrCondition = string.Format(" W.CREATELOGINID in (select ID from sys_user where FIND_IN_SET(distributor,getDiscChild({0})))", LogOnUser.Distributor);
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise))
                        pm.StrCondition = "  (w.EnterpriseID  in (0))";
                    else
                        pm.StrCondition = "  (w.EnterpriseID in (" + LogOnUser.JuniorEnterprise + "))";
                }
                else pm.StrCondition = "  1=1";
            }
            var result = _mservice.AlloGetPageList(ref pm, SearchModel);
            return Json(result);
        }

        //编辑
        public ActionResult EditAllot(int? id)
        {
            var model = _mservice.AllocationGetModel(id.ToString());
            ViewData["GoWarehouseId"] = SelWarehouseList(model.GoWarehouseId ?? 0, model.FromWarehouseId ?? 0);
            ViewData["FromWarehouseId"] = SelWarehouseList(model.FromWarehouseId ?? 0);
            return View(model);
        }
        //保存
        public ActionResult AllotSaveDate(AntiFleeing_Allocation model)
        {
            try
            {
                LogOnUserModel userModel = LogOnUser;
                model.ChangeLoginID = userModel.UserID;
                model.ChangeLoginName = userModel.RealName ?? userModel.LoginName;
                model.ChangeDate = DateTime.Now;
                model.Status = 1;//待导入
                int i = _mservice.AllocationUpdate(model);
                return Json(i);
            }
            catch (Exception)
            {
                throw;
            }
        }
        //删除
        public ActionResult DelAllocation(int? id)
        {
            AntiFleeing_Allocation model = new AntiFleeing_Allocation();
            model.ID = id;
            model.ViewDel = 1;//删除
            int i = _mservice.AllocationUpdate(model);
            return Json(i);
        }
        #endregion

        #region 产品退货
        //上传物流码
        public ActionResult ProReturnUploadTxt(string filePath)
        {
            if (LogOnUser.Distributor == 0)
            {
                return Json(-3);
            }
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_ProductReturn model = new AntiFleeing_ProductReturn();
            if (filePath != null)  // 如果有文件, 则保存到一个地址
            {
                StreamReader fsRead = new StreamReader(filePath, System.Text.Encoding.Default);
                string code = string.Empty;
                //int count = 0;
                int n = 0;
                while (!fsRead.EndOfStream)
                {
                    code = fsRead.ReadLine().TrimEnd(',');//读取一行数据
                    if (n == 0)
                    {
                        code = code.Replace("\t", "");
                        code = code.Replace("\n", "");
                        code = code.Replace("\r", "");
                        code = code.Replace("，", ",");
                        Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
                        if (code.Trim().Substring(0, 4) != ent.Code)
                        {
                            model.ViewDel = 1;
                            _mservice.ProReturnEdit(model);
                            fsRead.Close();
                            return Json(-2);
                        }
                        var list = _mservice.ListGetTable(code);
                        //判断是否冻结
                        if (list[0].Flag != 0)
                        {
                            fsRead.Close();
                            return Json(-4);
                        }
                        //当前码的最小标数量
                        model.DragNum = list.GroupBy(m => m.levv).Select(m => new
                        {
                            lev = m.Key,
                            count = m.Count(),
                        }).OrderBy(m => m.lev).Last().count;
                        code = list[0].Wl_Code;
                        //如果是经销商 则判断厂家是否给他出过库
                        if (LogOnUser.Distributor != 0)
                        {
                            var outInfo = _mservice.GetOutTable(code);
                            if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                            {
                                fsRead.Close();
                                return Json(-3);//您尚未权限操作该码
                            }
                        }
                        AntiFake_Digitcode dig = _mservice.GetTable(code);
                        if (dig.ProductId == 0)//尚未出入库
                        {
                            fsRead.Close();
                            return Json(-1);
                        }
                        // model.ProductID = _mservice.GetModel<AntiFleeing_ProductReturn>(code).ProductID;
                        model.ProductID = dig.ProductId.ToString();
                        // count = _mservice.SearchChildrenCount(code);
                    }
                    n++;
                }
                fsRead.Close();
                model.Num = n;
                model.DragNum = n * model.DragNum;
                //保存数据
                model.EnterpriseId = userModel.EnterpriseId;
                model.CreateLoginID = userModel.UserID;
                model.CreateLoginName = userModel.RealName ?? userModel.LoginName;
                model.CreateDate = DateTime.Now;
                model.FilePath = filePath;
                model.ViewDel = 0;
                model.ChangeDate = DateTime.Now;
                model.ChangeLoginID = userModel.UserID;
                model.ChangeLoginName = userModel.RealName ?? userModel.LoginName;
                model.DistributorId = userModel.Distributor;
                model.Type = 1;
              //  model.FormCode = "TH" + GetTimestamp(DateTime.Now);
                model = WipeNullHelper.WipeNull<AntiFleeing_ProductReturn>(model);//去空
                model.ID = _mservice.ProReturnAdd(model);
                return Json(model.ID);
            }
            else
            {
                return Json(-1);
            }
        }
        //  填写物流码
        public ActionResult ProReturnLittleCode(string BoxCode)
        {
            if (LogOnUser.Distributor == 0)
            {
                return Json("{'id':-1,'text':'当前身份不能进行退货'}");
            }
            BoxCode = BoxCode.Replace("\t", "");
            BoxCode = BoxCode.Replace("\n", "");
            BoxCode = BoxCode.Replace("\r", "");
            BoxCode = BoxCode.Replace("，", ",");
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_ProductReturn model = new AntiFleeing_ProductReturn();
          //  model.FormCode = "TH" + GetTimestamp(DateTime.Now);
            string[] arr = BoxCode.TrimEnd(',').Split(',');
            model.DragNum = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(arr[i].Trim()))
                {
                    return Json("{'id':-1,'text':'第" + i + "个码后面存在多余的字符！'}");
                }
                Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
                if (arr[i].Trim().Substring(0, 4) != ent.Code)
                {
                    return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码不属于当前企业！'}"); ;
                }
                //获取码分配信息
                var allotInfo = new CodeManage_Allot();
                if (ent.ID != LogOnUser.EnterpriseId)
                {
                    allotInfo = _mservice.CodeAllotInfo(ent.ID, LogOnUser.EnterpriseId, arr[i].Trim().Substring(4, 4));
                    if (allotInfo == null || allotInfo.AllotType == 2) { return Json("{'id':-1,'text':'第" + (i + 1) + "该码不属于当前企业或未分配！'}"); }
                }
                var dt = _mservice.GetTable(arr[i]);
                if (dt == null) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码不存在！'}");
                else
                {
                    if (allotInfo.AllotType == 0)//按号段分配
                    {
                        if (dt.ID < allotInfo.StartCode || dt.ID > allotInfo.EndCode)
                        {
                            return Json("{'id':-1,'text':'第" + (i + 1) + "该码不属于当前企业或未分配！'}");
                        }
                    }
                    model.ProductID = dt.ProductId.ToString();
                }
                var list = _mservice.ListGetTable(arr[i]);
                //判断是否冻结
                if (list[0].Flag != 0) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已冻结！'}");
                var parentCode = list[0].Wl_Code;
                if (parentCode != arr[i]) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码请分离后再操作！'}");
                //当前码的最小标数量
                model.DragNum += list.GroupBy(K => K.levv).Select(K => new
                {
                    lev = K.Key,
                    count = K.Count(),
                }).OrderBy(K => K.lev).Last().count;

                var outInfo = _mservice.GetOutTable(parentCode);
                if (LogOnUser.Distributor != 0)
                {
                    if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                    {
                        return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码您尚未权限操作！'}");//您尚未权限操作该码
                    }
                }
                else
                {
                    if (outInfo != null && outInfo.DistributorID != LogOnUser.Distributor)
                    {
                        return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已出库！'}");
                    }
                }
                AntiFleeing_WareHousingDetails dd = _mservice.GetIntoTable(parentCode, userModel.UserID.ToString());//查询入库信息
                if (dd == null)
                {
                    //AntiFleeing_OutboundDetails outModel = _mservice.GetOutTable(arr[i]); //查询出库信息
                    //if (outModel == null || outModel.DistributorID != LogOnUser.Distributor)
                    //{
                    return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码尚未入库！'}");
                    //  }
                }
            }

            model.FilePath = _mservice.WriteTxt(arr, "TH" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
            model.Type = 2;//退货
            model.EnterpriseId = userModel.EnterpriseId;
            model.CreateLoginID = userModel.UserID;
            model.CreateLoginName = userModel.RealName ?? userModel.LoginName;
            model.CreateDate = DateTime.Now;
            model.ViewDel = 0;
            model.Num = arr.Length;
            model.DistributorId = userModel.Distributor;
            model.Status = 0;//待导入
            model.CheckStatus = 0;//待确认
            int m = _mservice.ProReturnAdd(model);
            if (m <= 0) return Json("{'id':-1,'text':'提交失败！'}");
            return Json("{'id':" + m + "}");
        }
        public ActionResult SearchPageList(SearchModel SearchModel, int pageIndex, int pageSize = 15)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = "  ID" + " " + "desc";
            if (LogOnUser.Distributor != 0)//经销商
            {
                //  pm.StrCondition = "  w.CreateLoginID in (select ID from sys_user where distributor in (SELECT ID from antifleeing_distributor where FIND_IN_SET(id,getDiscChild(" + LogOnUser.Distributor + "))))";
                pm.StrCondition = string.Format(" W.CREATELOGINID in (select ID from sys_user where FIND_IN_SET(distributor,getDiscChild({0})))", LogOnUser.Distributor);
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise))
                        pm.StrCondition = "  w.EnterpriseId  in (0)";
                    else
                        pm.StrCondition = "  w.EnterpriseId in (" + LogOnUser.JuniorEnterprise + ")";
                }
                else pm.StrCondition = "  1=1";
            }
            LogOnUserModel userModel = LogOnUser;
            var result = _mservice.ReturnGetPageList(ref pm, SearchModel);
            return Json(result);
        }
        //编辑
        public ActionResult EditReturn(int? id)
        {
            var model = _mservice.ProReturnGetModel(id.ToString());
            return View(model);
        }
        //保存
        public ActionResult ProReturnSaveDate(AntiFleeing_ProductReturn model)
        {
            try
            {
                LogOnUserModel userModel = LogOnUser;
                model.ChangeLoginID = userModel.UserID;
                model.ChangeLoginName = userModel.RealName ?? userModel.LoginName;
                model.ChangeDate = DateTime.Now;
                model.CheckStatus = 1;//已提交申请
                int i = _mservice.ProReturnUpdate(model);
                return Json(i);
            }
            catch (Exception)
            {
                throw;
            }
        }
        //删除
        public ActionResult ProReturnDel(int? id)
        {
            AntiFleeing_ProductReturn model = new AntiFleeing_ProductReturn();
            model.ID = id;
            model.ViewDel = 1;//删除
            int i = _mservice.ProReturnUpdate(model);
            return Json(i);
        }
        //取消
        public ActionResult ProCansole(string formCode, string filePath)
        {
            try
            {
                if (!string.IsNullOrEmpty(formCode))
                {

                    if (!string.IsNullOrEmpty(filePath))
                    {
                        StreamReader fsRead = new StreamReader(filePath, System.Text.Encoding.Default);
                        string codeStr = "";
                        int n = 1;
                        string str = "";
                        while (!fsRead.EndOfStream)
                        {
                            string code = fsRead.ReadLine();
                            code = code.Replace("，", ",");
                            code = code.Replace("\t", "");
                            code = code.Replace("\n", "");
                            code = code.Replace("\r", "");
                            code = code.TrimEnd(',');
                            codeStr += code + ',';
                            if (str == "") str = "('" + formCode + "','" + code + "','取消退货申请')";
                            else str += ",('" + formCode + "','" + code + "','取消退货申请')";
                            if (n % 1000 == 0)
                            {
                                _mservice.FrozenOrThaw(codeStr.TrimEnd(','), 0);
                                _mservice.AddErrorReturnPro(str);
                                str = "";
                                codeStr = string.Empty;
                                n = 0;
                            }
                            n++;
                        }
                        fsRead.Close();
                        if (n > 0 && n < 1000)
                        {
                            _mservice.FrozenOrThaw(codeStr.TrimEnd(','), 0);//解冻
                            _mservice.AddErrorReturnPro(str);
                        }
                        //更改状态
                        int i = _mservice.ProReturnCansole(formCode);
                        return Json("取消成功！");
                    }
                }
                return Json("取消失败！");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }

        }
        #endregion

        #region 产品调货
        public ActionResult CargoShowData(int id)
        {
            var model = _mservice.GetCargoId(id);
            ViewBag.model = model;
            return View();
        }
        //上传物流码
        public ActionResult TranUploadTxt(string filePath)
        {
            if (LogOnUser.Distributor == 0)
            {
                return Json(-3);
            }
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_Transshipment model = new AntiFleeing_Transshipment();
            if (filePath != null)  // 如果有文件, 则保存到一个地址
            {
                StreamReader fsRead = new StreamReader(filePath, System.Text.Encoding.Default);
                string code = string.Empty;
                int n = 0;
                while (!fsRead.EndOfStream)
                {
                    if (n == 0)
                    {
                        code = fsRead.ReadLine().TrimEnd(',');//读取一行数据
                        code = code.Replace("\t", "");
                        code = code.Replace("\n", "");
                        code = code.Replace("\r", "");
                        code = code.Replace("，", ",");
                        Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
                        if (code.Trim().Substring(0, 4) != ent.Code)
                        {
                            fsRead.Close();
                            return Json(-2);
                        }
                        var list = _mservice.ListGetTable(code);
                        //判断是否冻结
                        if (list[0].Flag != 0)
                        {
                            fsRead.Close();
                            return Json(-4);
                        }
                        //当前码的最小标数量
                        model.DragNum = list.GroupBy(m => m.levv).Select(m => new
                        {
                            lev = m.Key,
                            count = m.Count(),
                        }).OrderBy(m => m.lev).Last().count;
                        code = list[0].Wl_Code;
                        //如果是经销商 则判断厂家是否给他出过库
                        if (LogOnUser.Distributor != 0)
                        {
                            var outInfo = _mservice.GetOutTable(code);
                            if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                            {
                                fsRead.Close();
                                return Json(-3);//您尚未权限操作该码
                            }
                        }
                        AntiFake_Digitcode digModel = _mservice.GetTable(code);
                        if (digModel.ProductId == 0)
                        {
                            fsRead.Close();
                            //删除记录
                            return Json(-1);
                        }
                        model.ProductID = digModel.ProductId.ToString();
                    }
                    n++;
                }
                fsRead.Close();
                model.Num = n;
                model.DragNum = n * model.DragNum;
                //保存数据
                model.EnterpriseID = userModel.EnterpriseId;
                model.CreateLoginID = userModel.UserID;
                model.CreateLoginName = userModel.LoginName;
                model.CreateDate = DateTime.Now;
                model.FilePath = filePath;
                model.ViewDel = 0;
                model.ChangeDate = DateTime.Now;
                model.ChangeLoginID = userModel.UserID;
                model.ChangeLoginName = userModel.LoginName;
                model.Status = 0;//待编辑
                model.Type = 1;
                // model.FormCode = "DH" + GetTimestamp(DateTime.Now);
                model.FromDistributor = userModel.Distributor;
                model = WipeNullHelper.WipeNull<AntiFleeing_Transshipment>(model);//去空
                model.ID = _mservice.TranAdd(model);
                return Json(model.ID);
            }
            else
            {
                return Json(-1);
            }
        }
        //填写物流码
        public ActionResult TranLittleCode(string BoxCode)
        {
            if (LogOnUser.Distributor == 0)
            {
                return Json("{'id':-1,'text':'当前身份不能进行调货'}");
            }
            BoxCode = BoxCode.Replace("\t", "");
            BoxCode = BoxCode.Replace("\n", "");
            BoxCode = BoxCode.Replace("\r", "");
            BoxCode = BoxCode.Replace("，", ",");
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_Transshipment model = new AntiFleeing_Transshipment();
            // model.FormCode = "DH" + GetTimestamp(DateTime.Now);
            string[] arr = BoxCode.TrimEnd(',').Split(',');
            model.DragNum = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(arr[i].Trim()))
                {
                    return Json("{'id':-1,'text':'第" + i + "个码后面存在多余的字符！'}");
                }
                Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
                if (arr[i].Trim().Substring(0, 4) != ent.Code)
                {
                    return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码不属于当前企业！'}"); ;
                }
                var allotInfo = new CodeManage_Allot();
                if (ent.ID != LogOnUser.EnterpriseId)
                {
                    allotInfo = _mservice.CodeAllotInfo(ent.ID, LogOnUser.EnterpriseId, arr[i].Trim().Substring(4, 4));
                    if (allotInfo == null || allotInfo.AllotType == 2) { return Json("{'id':-1,'text':'第" + (i + 1) + "该码不属于当前企业或未分配！'}"); }
                }
                var dt = _mservice.GetTable(arr[i]);
                if (dt == null) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码不存在！'}");
                else
                {
                    if (allotInfo.AllotType == 0)//按号段分配
                    {
                        if (dt.ID < allotInfo.StartCode || dt.ID > allotInfo.EndCode)
                        {
                            return Json("{'id':-1,'text':'第" + (i + 1) + "该码不属于当前企业或未分配！'}");
                        }
                    }
                    model.ProductID = dt.ProductId.ToString();
                }
                var list = _mservice.ListGetTable(arr[i]);
                //判断是否冻结
                if (list[0].Flag != 0) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已冻结！'}");
                var parentCode = list[0].Wl_Code;
                if (parentCode != arr[i]) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码请分离后再操作！'}");
                //当前码的最小标数量
                model.DragNum += list.GroupBy(K => K.levv).Select(K => new
                {
                    lev = K.Key,
                    count = K.Count(),
                }).OrderBy(K => K.lev).Last().count;
                var outInfo = _mservice.GetOutTable(parentCode);
                if (LogOnUser.Distributor != 0)
                {
                    if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                    {
                        return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码您尚未权限操作！'}");//您尚未权限操作该码
                    }
                }
                else
                {
                    if (outInfo != null && outInfo.DistributorID != LogOnUser.Distributor)
                    {
                        return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已出库！'}");
                    }
                }
                AntiFleeing_WareHousingDetails dd = _mservice.GetIntoTable(parentCode, userModel.UserID.ToString());//查询入库信息
                if (dd == null)
                {
                    return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码尚未入库！'}");
                }

            }

            model.FilePath = _mservice.WriteTxt(arr, "DH" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
            model.Type = 2;
            model.EnterpriseID = userModel.EnterpriseId;
            model.CreateLoginID = userModel.UserID;
            model.CreateLoginName = userModel.LoginName;
            model.CreateDate = DateTime.Now;
            model.ViewDel = 0;
            model.Num = arr.Length;
            model.Status = 0;//待导入
            model.CheckStatus = 0;//待提交
            model.FromDistributor = userModel.Distributor;
            int m = _mservice.TranAdd(model);
            if (m <= 0) return Json("{'id':-1,'text':'提交失败！}'");
            return Json("{'id':" + m + "}");
        }
        //分页查询
        public ActionResult TranPageList(SearchModel SearchModel, int pageIndex = 1, int pageSize = 15)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = "  ID" + " " + "desc";
            if (LogOnUser.Distributor != 0)//经销商
            {
                pm.StrCondition = string.Format(" W.CREATELOGINID in (select ID from sys_user where FIND_IN_SET(distributor,getDiscChild({0})))", LogOnUser.Distributor);
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise))
                        pm.StrCondition = "  (w.EnterpriseId  in (0))";
                    else
                        pm.StrCondition = "  (w.EnterpriseId in (" + LogOnUser.JuniorEnterprise + "))";
                }
                else pm.StrCondition = "  1=1";

            }
            var result = _mservice.TranGetPageList(ref pm, SearchModel);
            return Json(result);
        }
        //编辑
        public ActionResult EditCargo(int? id)
        {
            var model = _mservice.TranGetModel(id.ToString());
            return View(model);
        }
        //保存
        public ActionResult TranSaveDate(AntiFleeing_Transshipment model)
        {
            LogOnUserModel userModel = LogOnUser;
            model.ChangeLoginID = userModel.UserID;
            model.ChangeLoginName = userModel.LoginName;
            model.ChangeDate = DateTime.Now;
            model.CheckStatus = 1;
            int i = _mservice.TranUpdate(model);
            return Json(i);
        }
        //删除
        public ActionResult TranDel(int? id)
        {
            AntiFleeing_Transshipment model = new AntiFleeing_Transshipment();
            model.ID = id;
            model.ViewDel = 1;//删除
            int i = _mservice.TranUpdate(model);
            return Json(i);
        }
        //取消
        public ActionResult ProTranCansole(string formCode, string filePath)
        {
            try
            {
                if (!string.IsNullOrEmpty(formCode))
                {
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        StreamReader fsRead = new StreamReader(filePath, System.Text.Encoding.Default);
                        string codeStr = "";
                        string str = "";
                        int n = 0;
                        while (!fsRead.EndOfStream)
                        {
                            string code = fsRead.ReadLine();
                            code = code.Replace("，", ",");
                            code = code.Replace("\t", "");
                            code = code.Replace("\n", "");
                            code = code.Replace("\r", "");
                            code = code.TrimEnd(',');
                            if (str == "") str = "('" + formCode + "','" + code + "','取消调货')";
                            else str += ",('" + formCode + "','" + code + "','取消调货')";
                            codeStr += code + ',';
                            if (n % 1000 == 0)
                            {
                                _mservice.FrozenOrThaw(codeStr.TrimEnd(','), 0);
                                _mservice.AddErrorTranPro(str);
                                str = "";
                                codeStr = string.Empty;
                                n = 0;
                            }
                        }
                        fsRead.Close();
                        if (n > 0 && n < 1000)
                        {
                            _mservice.AddErrorTranPro(str);
                            _mservice.FrozenOrThaw(codeStr.TrimEnd(','), 0);//解冻
                        }
                        //更改状态
                        int i = _mservice.TranCansole(formCode);
                        return Json("取消成功！");
                    }
                }
                return Json("取消失败！");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }

        }
        #endregion

        #region 产品出库
        public ActionResult EditOut(int? id)//编辑
        {
            AntiFleeing_IOWarehouse model = _mservice.GetWarehouseModel((int)id);
            ViewData["WarehouseId"] = SelWarehouseList(int.Parse(model.WarehouseId.ToString()));
            ViewData["ProductID"] = SelProductList(model.ProductID);
            ViewData["SaleAreaId"] = SelSaleAreaList(int.Parse(model.SaleAreaId.ToString()));
            //ViewData["Distributor"] = SelDistributorList((int)model.SaleAreaId, (int)model.Distributor);
            return View(model);
        }
        // 分页查询
        public ActionResult OutPageList(SearchModel SearchModel, int pageIndex = 1, int pageSize = 15)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = "  ID" + " " + "desc";
            if (LogOnUser.Distributor != 0)//经销商
            {
                // pm.StrCondition = " (w.CreateLoginID=" + LogOnUser.UserID + " or w.CreateLoginID in (select ID from sys_user where  ViewDel=0 and ChangeLoginID=" + LogOnUser.UserID + "))";
                pm.StrCondition = string.Format(" W.CREATELOGINID in (select ID from sys_user where FIND_IN_SET(distributor,getDiscChild({0})))", LogOnUser.Distributor);
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise))
                        pm.StrCondition = "  (w.EnterpriseID  in (0))";
                    else
                        pm.StrCondition = "  (w.EnterpriseID in (" + LogOnUser.JuniorEnterprise + "))";
                }
                else pm.StrCondition = " 1=1";
            }
            var result = _mservice.OutGetPageList(ref pm, SearchModel);
            return Json(result);
        }
        //上传物流码
        public ActionResult OutUploadTxt(string filePath)
        {
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_IOWarehouse model = new AntiFleeing_IOWarehouse();
            if (filePath != null)  // 如果有文件, 则保存到一个地址
            {
                StreamReader fsRead = new StreamReader(filePath, System.Text.Encoding.Default);
                string code = "";
                int n = 0;
                while (!fsRead.EndOfStream)
                {
                    code = fsRead.ReadLine().Replace(",", "");//读取一行数据
                    n++;
                }
                fsRead.Close();
                code = code.Replace("\t", "");
                code = code.Replace("\n", "");
                code = code.Replace("\r", "");
                code = code.Replace("，", ",");
                Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
                if (code.Trim().Substring(0, 4) != ent.Code)
                {
                    model.ViewDel = 1;
                    return Json(-2);
                }

                var list = _mservice.ListGetTable(code);
                //判断是否冻结
                if (list[0].Flag != 0)
                {
                    fsRead.Close();
                    return Json(-4);
                }
                //当前码的最小标数量
                model.DragNum += list.GroupBy(m => m.levv).Select(m => new
                {
                    lev = m.Key,
                    count = m.Count(),
                }).OrderBy(m => m.lev).Last().count;
                code = list[0].Wl_Code;
                //如果是经销商 则判断厂家是否给他出过库
                if (LogOnUser.Distributor != 0)
                {
                    var outInfo = _mservice.GetOutTable(code);
                    if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                    {
                        return Json(-3);//您尚未权限操作该码
                    }
                }
                AntiFleeing_IOWarehouse anti = _mservice.GetModel<AntiFleeing_IOWarehouse>(code);
                model.ProductID = "0";
                if (anti.ProductID != null) model.ProductID = anti.ProductID;
                var info = _mservice.GetIOWarehouseInfo(code, LogOnUser.EnterpriseId);
                if (info != null) model.WarehouseId = info.WarehouseId ?? 0;
                model.Num = n;
                model.DragNum = n * model.DragNum;
                //保存数据
                model.EnterpriseID = userModel.EnterpriseId;
                model.CreateLoginID = userModel.UserID;
                model.CreateLoginName = userModel.RealName ?? userModel.LoginName;
                model.CreateDate = DateTime.Now;
                //  model.FormCode = "CK" + GetTimestamp(DateTime.Now);
                model.FormType = 2;//出库
                model.FilePath = filePath;
                model.ViewDel = 0;
                model.ChangeDate = DateTime.Now;
                model.Type = 1;
                model = WipeNullHelper.WipeNull<AntiFleeing_IOWarehouse>(model);
                model.Id = _mservice.Add(model);
                return Json(model.Id);
            }
            else
            {
                return Json(-1);
            }
        }
        public ActionResult OutLittleCode(string BoxCode)
        {
            BoxCode = BoxCode.Replace("\t", "");
            BoxCode = BoxCode.Replace("\n", "");
            BoxCode = BoxCode.Replace("\r", "");
            BoxCode = BoxCode.Replace("，", ",");
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_IOWarehouse model = new AntiFleeing_IOWarehouse();
            // model.FormCode = "CK" + GetTimestamp(DateTime.Now);
            AntiFake_Digitcode digModel = new AntiFake_Digitcode();
            string[] arr = BoxCode.TrimEnd(',').Split(',');
            Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
            model.DragNum = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(arr[i].Trim()))
                {
                    return Json("{'id':-1,'text':'第" + i + "个码后面存在多余的字符！'}");
                }
                if (arr[i].Trim().Substring(0, 4) != ent.Code)
                {
                    return Json("{'id':-1,'text':'第" + (i + 1) + "码不属于当前企业！'}"); ;
                }
                //码分配
                var allotInfo = new CodeManage_Allot();
                if (ent.ID != LogOnUser.EnterpriseId)
                {
                    allotInfo = _mservice.CodeAllotInfo(ent.ID, LogOnUser.EnterpriseId, arr[i].Trim().Substring(4, 4));
                    if (allotInfo == null || allotInfo.AllotType == 2) { return Json("{'id':-1,'text':'第" + (i + 1) + "该码不属于当前企业或未分配！'}"); }
                }
                var list = _mservice.ListGetTable(arr[i]);
                //判断是否冻结
                if (list[0].Flag != 0) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码已冻结！'}");
                //当前码的最小标数量
                model.DragNum += list.GroupBy(K => K.levv).Select(K => new
                {
                    lev = K.Key,
                    count = K.Count(),
                }).OrderBy(K => K.lev).Last().count;
                var parentCode = list[0].Wl_Code;
                digModel = _mservice.GetTable(arr[i]);
                if (digModel == null) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码不存在！'}");
                else
                {
                    if (allotInfo.AllotType == 0)//按号段分配
                    {
                        if (digModel.ID < allotInfo.StartCode || digModel.ID > allotInfo.EndCode)
                        {
                            return Json("{'id':-1,'text':'第" + (i + 1) + "该码不属于当前企业或未分配！'}");
                        }
                    }
                    if (i == 0) model.ProductID = digModel.ProductId.ToString();
                    else
                    {
                        if (model.ProductID != digModel.ProductId.ToString())
                        {
                            return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码与其他码绑定的产品不同！'}");
                        }
                    }
                }
                //如果是经销商 则判断厂家是否给他出过库
                if (LogOnUser.Distributor != 0)
                {
                    var outInfo = _mservice.GetOutTable(arr[i]);
                    if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                    {
                        //上级是否出库
                        outInfo = _mservice.GetOutTable(parentCode);
                        if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                            return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码您尚未权限操作！'}");//您尚未权限操作该码
                    }
                    //判断码上级是否出库
                    var isOutInfo = _mservice.GetOutInfo(parentCode, LogOnUser.EnterpriseId);
                    if (isOutInfo != null)
                    {
                        if (isOutInfo.ChangeLoginID == LogOnUser.UserID)
                        {
                            return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码您已出库，请勿重复！'}");
                        }
                    }
                    model.WarehouseId = _mservice.GetWarehouseInfo(arr[0], 0, LogOnUser.UserID) == null ? 0 : _mservice.GetWarehouseInfo(arr[0], 0, LogOnUser.UserID).ID;
                }
                else
                {
                    //判断当前机构是否出库
                    var isOutInfo = _mservice.GetOutInfo(parentCode, LogOnUser.EnterpriseId);
                    if (isOutInfo != null && isOutInfo.DistributorID != 0) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码您已出库，请勿重复！'}");
                    model.WarehouseId = _mservice.GetWarehouseInfo(arr[0], LogOnUser.EnterpriseId, 0) == null ? 0 : _mservice.GetWarehouseInfo(arr[0], 0, LogOnUser.UserID).ID;
                }

                //出库自动拆箱
                if (parentCode != arr[i])
                {
                    bool isTrue = CodeInfoImport(parentCode, arr[i], 4, parentCode);
                    if (!isTrue) return Json("{'id':-1,'text':'第" + (i + 1) + "个箱码出库拆箱时失败！'}");
                }
            }

            model.FilePath = _mservice.WriteTxt(arr, "CK" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
            model.Type = 2;
            model.EnterpriseID = userModel.EnterpriseId;
            model.CreateLoginID = userModel.UserID;
            model.CreateLoginName = userModel.RealName ?? userModel.LoginName;
            model.CreateDate = DateTime.Now;
            model.ViewDel = 0;
            model.Num = arr.Length;
            model.FormType = 2;//出库
            model.ChangeDate = DateTime.Now;
            model = WipeNullHelper.WipeNull<AntiFleeing_IOWarehouse>(model);
            int id = _mservice.Add(model);
            return Json("{'id':" + id + "}");
        }
        #endregion

        #region 处理状态
        public ActionResult ProcessPageList(string key, int pageIndex = 1, int pageSize = 15)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = "  ID" + " " + "desc";
            if (LogOnUser.Distributor != 0)//经销商
            {
                pm.StrCondition = "  type=2 and CreateLoginID in ( select ID from  Sys_User where Distributor in ( select ID from AntiFleeing_Distributor where parentId=" + LogOnUser.Distributor + "))";
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {

                    pm.StrCondition = "  CreateLoginID in(select ID from Sys_User where  EnterpriseId=" + LogOnUser.EnterpriseId + ") ";
                }
                else pm.StrCondition = "  1=1";

            }
            LogOnUserModel userModel = LogOnUser;
            var result = _mservice.ProcTypeGetPageList(ref pm, key);
            return Json(result);
        }
        //退货状态处理
        public ActionResult PendingAllot(string formCode, int? type)
        {
            AntiFleeing_ProcessingType model = new AntiFleeing_ProcessingType();
            if (type == 1)//调货
            {
                model = _mservice.DHProcTypeModel(formCode);
            }
            if (type == 2)//退货
            {
                model = _mservice.THProcTypeModel(formCode);
                if (model.GoWarehouseId == null) model.GoWarehouseId = 0;
                ViewData["WarehouseId"] = SelWarehouseList(int.Parse(model.GoWarehouseId.ToString()));
            }
            model.Type = type;
            return View(model);
        }
        public JsonResult THAgree(string formCode, int? warehouseId = 0, int id = 0)
        {
            //退货表中的去向经销商和去向仓库改为当前登录用户的经销商身份
            LogOnUserModel userModel = LogOnUser;
            AntiFleeing_ProductReturn returnModel = new AntiFleeing_ProductReturn();
            returnModel.FormCode = formCode;
            returnModel.GoDistributor = userModel.Distributor;
            returnModel.GoWarehouseId = warehouseId;
            returnModel.CheckStatus = 3;//审核成功
            int m = _mservice.ProReturnEdit(returnModel);
            if (m <= 0) return Json(m, JsonRequestBehavior.AllowGet);
            int n = _mservice.ProcTypeUpdateStatus(1, id);
            return Json(n, JsonRequestBehavior.AllowGet);
        }
        public JsonResult DHAgree(string formCode, int? saleAreaId, int? distributor, int id = 0)
        {
            int m = _mservice.EditDistributor(formCode, (int)distributor, (int)saleAreaId, 3);
            if (m <= 0) return Json(m, JsonRequestBehavior.AllowGet);
            int n = _mservice.ProcTypeUpdateStatus(1, id);
            return Json(n, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Agree()
        {
            ViewData["SaleAreaId"] = SelSaleAreaList(0);
            return View();
        }
        //拒绝
        public ActionResult Disgree(string formCode, int? type, int id = 0)
        {
            int i = 0;
            if (type == 1)//调货
            {
                i = _mservice.UpdateStatus(2, formCode, "antifleeing_transshipment  ", 4, id);
            }
            if (type == 2)
            {
                i = _mservice.UpdateStatus(2, formCode, "AntiFleeing_ProductReturn", 4, id);
            }
            return Json(i);
        }

        //返回给上级
        public ActionResult BackSuperior(string formCode, int id = 0)
        {
            if (LogOnUser.Distributor == 0) return Json(-2);
            //更改状态
            int n = _mservice.ProcTypeUpdateStatus(3, id);//返回上级
            if (n > 0)
            {
                //添加处理状态
                AntiFleeing_ProcessingType typeModel = new AntiFleeing_ProcessingType();
                typeModel.FormCode = formCode;
                typeModel.Type = 2;//退货
                typeModel.ViewDel = 0;
                typeModel.CreateLoginID = LogOnUser.UserID;
                typeModel.CreateLoginName = LogOnUser.LoginName;
                typeModel.CreateDate = DateTime.Now;
                typeModel.Status = 0;//未审核
                typeModel.EnterpriseID = LogOnUser.EnterpriseId;
                int m = _mservice.ProcTypeAdd(typeModel);
                return Json(m);
            }
            else
            {
                return Json(-1);
            }
        }
        #endregion

        #region 窜货验证

        public ActionResult FleeGoodsVerify()
        {
            return View();
        }
        public ActionResult FleeGoodsResult(string key)
        {
            try
            {
                key = key.Trim();
                //判断当前码是否属于当前机构
                if (LogOnUser.EnterpriseId != 1)
                {
                    Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);
                    if (key.Trim().Substring(0, 4) != ent.Code) return Json("");
                }
                // 查出库表
                AntiFleeing_OutboundDetails model = _mservice.GetTableByCode(key);
                if (model == null)
                {
                    var list = _mservice.ListGetTable(key);
                    var parentCode = list[0].Wl_Code;
                    //上级是否出库信息
                    model = _mservice.GetParentTableByCode(parentCode);
                    if (model == null) return Json("");
                    else return Json(Model(model.FormCode, key, model.DistributorID));
                }
                else
                {
                    return Json(Model(model.FormCode, key, model.DistributorID));
                }
            }
            catch (Exception)
            {
                return Json("");
            }
        }
        public FleeingProving Model(string formCode, string code, int disId)
        {
            FleeingProving FPModel = new FleeingProving();
            AntiFleeing_IOWarehouse model = _mservice.GetModelByFormCode(formCode);
            //发往某片区的某个等级的经销商某某

            AntiFleeing_Distributor discModel = _mservice.GetTableById(disId);
            FPModel.CompanyName = model.EnterpriseName;
            FPModel.ProductName = model.ProductName;
            if (discModel != null)
            {
                DateTime date = (DateTime)model.CreateDate;
                FPModel.ChuKuDate = date.ToString("yyyy-MM-dd HH:mm:ss");
                FPModel.FWDistributor = discModel.Name;
                FPModel.Contact = discModel.Contacts;
                FPModel.Address = discModel.ProvinceName + "-" + discModel.CityName + "-" + discModel.RegionName;
                FPModel.Precinct = discModel.JurisdictionPrivanceName + "-" + discModel.JurisdictionCityName + "-" + discModel.JurisdictionRegionName;
                if (discModel.IsCrossArea.ToString() == "1")
                    FPModel.CrossArea = discModel.AcrossPrivanceName + "-" + discModel.AcrossCityName + "-" + discModel.AcrossRegionName;
                else FPModel.CrossArea = "无";
                FPModel.SaleArea = discModel.SalesArea;
                FPModel.FWSaleArea = model.SaleAreaName;
                FPModel.DisLevelName = discModel.DisLevelName;
            }
            var levelModel = _mservice.GetDistLevelModel(LogOnUser.EnterpriseId);
            FPModel.MaxLevel = levelModel == null ? "" : levelModel.LevelName;
            return FPModel;
        }
        #endregion

        #region 操作记录
        public ActionResult OperationRecords()
        {
            return View();
        }
        public ActionResult RecordsList(string key, int pageIndex = 1, int pageSize = 15)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            var result = _mservice.RecordList(ref pm, key);
            return Json(result);
        }
        #endregion

        #region 出库记录
        public ActionResult OutRecords()
        {
            return View();
        }
        public ActionResult OutRecordsList(string key)
        {
            if (LogOnUser.EnterpriseId == 1)
            {
                return Json(1);//该物流码不属于当前企业
            }
            Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);
            if (key.Trim().Substring(0, 4) != ent.Code && LogOnUser.EnterpriseId != 1)
            {
                return Json(1);//该物流码不属于当前企业
            }
            //  string tableName = "nbcodemain.AntiFake_Digitcode" + key.Substring(0, 6);
            var list = _mservice.ListGetTable(key);
            //关联码
            var parentCode = list[0].Wl_Code;
            var Alllist = _mservice.OutRecordList(key, parentCode);
            if (Alllist == null) return Json(2);
            List<AntiFleeing_OutRecords> newList = new List<AntiFleeing_OutRecords>();
            foreach (var item in Alllist)
            {
                AntiFleeing_OutRecords model = item;
                var disModel = _mservice.GetDistributor(item.Distributor);
                model.DistributorName = disModel.Name;
                model.DisLevelName = disModel.LevelName;
                newList.Add(model);
                if (item.Distributor != item.DistributorID)//如果两个经销商不等
                {
                    model = new AntiFleeing_OutRecords();
                    model.Distributor = item.DistributorID;
                    model.CreateDate = item.ChangeDate;
                    if (item.DistributorID != 0)
                    {
                        var dModel = _mservice.GetDistributor(item.DistributorID);
                        model.DistributorName = disModel.Name;
                        model.DisLevelName = disModel.LevelName;
                    }
                    else
                    {
                        //厂家
                        model.CreateloginName = disModel.Name;
                        model.DistributorName = _mservice.GetEnterprisebyCode(key.Substring(0, 4).ToString()).EnterpriseName;
                        model.DisLevelName = "厂家/企业";
                    }
                    newList.Add(model);
                }
            }
            return Json(newList);
        }
        #endregion

        #region 台账统计
        public ActionResult OurLife()
        {
            return View();
        }
        public ActionResult OurLifeList(string key)
        {
            if (LogOnUser.EnterpriseId == 1)
            {
                return Json(1);//该物流码不属于当前企业
            }
            if (string.IsNullOrEmpty(key)) return Json(null);
            if (key.Trim().Substring(0, 4) != LogOnUser.ECode.Substring(0, 4) && LogOnUser.EnterpriseId != 1)
            {
                return Json(1);//该物流码不属于当前企业
            }
            var list = _mservice.ListGetTable(key);
            if (list == null) return Json(2);
            //上级码
            var parentCode = list[0].Wl_Code;
            string productName = _mservice.getProductName(parentCode);
            var recordlist = _mservice.OurLife(key, parentCode, productName);
            if (recordlist == null) return Json(2);
            return Json(recordlist);
        }
        #endregion

        #region 拆箱
        public ActionResult SliptCase()
        {
            return View();
        }
        public ActionResult DoOfSliptCase(string code)
        {
            code = code.Trim();
            AntiFleeing_DevanningRecords record = new AntiFleeing_DevanningRecords();
            record.CZCode = code;
            var list = new List<V_ListBox>();
            string result = Check_Out(code, out list);
            if (!string.IsNullOrEmpty(result)) return Json(result);
            record.Type = 1;//拆箱
            record.CreateBy = LogOnUser.UserID;
            record.CreateOn = DateTime.Now;

            _mservice.AddDevanningRecords(record);
            _mservice.AddRecordsforSplit(code);
            int i = _mservice.SlipCase(code);
            if (i < 0) return Json("拆箱失败");
            return Json("拆箱成功");
        }
        #endregion
        public static string GetTimestamp(DateTime d)
        {
            TimeSpan ts = d.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0);
            return Math.Floor(ts.TotalMilliseconds).ToString();    //精确到毫秒
        }
        public string Check_Out(string code, out List<V_ListBox> _list)
        {
            var list = _mservice.GetParentCode(code);
            _list = list;
            if (list == null) return "码不存在";
            //判断是否冻结
            if (list[0].Flag != 0) return "该码已冻结";
            Organization_Enterprise ent = _mservice.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId);//获取最上级的机构信息
            //获取码分配信息
            var allotInfo = new CodeManage_Allot();
            if (ent.ID != LogOnUser.EnterpriseId)
            {
                allotInfo = _mservice.CodeAllotInfo(ent.ID, LogOnUser.EnterpriseId, code.Trim().Substring(4, 4));
                if (allotInfo == null || allotInfo.AllotType == 2) { return "该码不属于当前企业或未分配"; }
            }
            if (allotInfo.AllotType == 0)//按号段分配
            {
                if (list[list.Count - 1].ID < allotInfo.StartCode || list[list.Count - 1].ID > allotInfo.EndCode)
                {
                    return "该码不属于当前企业或未分配";
                }
            }

            if (LogOnUser.EnterpriseId != 1 && code.Substring(0, 4) != LogOnUser.ECode.Substring(0, 4)) return "该码不属于当前机构!";
            var outInfo = _mservice.GetOutTable(list[0].Wl_Code);//出库信息
            if (LogOnUser.Distributor != 0)
            {
                if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                {
                    return "您尚未权限操作该码";
                }
            }
            else
            {
                if (outInfo != null)
                {
                    return "该码已出库";
                }
            }
            return null;
        }
    }
}